package com.itheima.proxydemo2;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class ProxyUtil {
    /*public static UserService createProxy(UserServiceImpl obj) {
        UserService proxy = (UserService) Proxy.newProxyInstance(ProxyUtil.class.getClassLoader(),
                obj.getClass().getInterfaces(), new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        long start = System.currentTimeMillis();
                        Object res = method.invoke(obj, args);  //调用目标对象的方法
                        long end = System.currentTimeMillis();
                        System.out.println(method.getName() +"方法耗时：" + (end - start)/1000.0 + "s");
                        return res;
                    }
                });
        return proxy;
    }*/

    //通用的代理方法
    public static <T> T createProxy(T obj) {
        T proxy = (T) Proxy.newProxyInstance(ProxyUtil.class.getClassLoader(),
                obj.getClass().getInterfaces(), new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        long start = System.currentTimeMillis();
                        Object res = method.invoke(obj, args);  //调用目标对象的方法
                        long end = System.currentTimeMillis();
                        System.out.println(method.getName() +"方法耗时：" + (end - start)/1000.0 + "s");
                        return res;
                    }
                });
        return proxy;
    }
}
